package com.snow.service.user.impl;

import com.snow.constant.ErrorConstant;
import com.snow.dao.UserDao;
import com.snow.exception.SiteException;
import com.snow.pojo.model.UserDomain;
import com.snow.service.user.UserService;
import com.snow.utils.TaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Description:
 * @author: snow
 * @Date: 2020-01-18
 **/
@Service
public class UserServiceImpl implements UserService {
    private static Logger logger = Logger.getLogger(UserServiceImpl.class);
    @Autowired
    private UserDao userDao;

    /**
     * 更新用户信息
     * @param userDomain
     * @return
     */
    @Override
    public int updateUserInfo(UserDomain userDomain) {
        if(userDomain == null){
            throw SiteException.withErrorCode(ErrorConstant.Commons.PARAM_IS_EMPTY);
        }
        return userDao.updateUserInfo(userDomain);
    }

    @Override
    public UserDomain login(String username, String password) {
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw SiteException.withErrorCode(ErrorConstant.Commons.PARAM_IS_EMPTY);
        }
        String pwd = TaleUtils.MD5encode(username + password);
        UserDomain user = userDao.getUserByCond(username,pwd);
        if(user == null){
            throw SiteException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_ERROR);

        }
        return user;
    }

    @Override
    public UserDomain getUserInfoById(Integer uid) {
        logger.info("Enter getUserInfoById Method");
        return userDao.getUserInfoById(uid);
    }

    @Override
    public UserDomain getUserByUsername(String username) {
        return userDao.getUserByUsername(username);
    }

    @Override
    public void registry(UserDomain userDomain) {
        logger.info("Enter registry");
        if(userDomain == null || StringUtils.isBlank(userDomain.getUsername()) ||
                StringUtils.isBlank(userDomain.getPassword())){
            throw SiteException.withErrorCode("用户名和密码不能为空！");
        }
        logger.info("username =====>" + userDomain.getUsername());
        String salt = UUID.randomUUID().toString();
        String pwd = new Sha256Hash(userDomain.getPassword(),salt,1024).toBase64();
        userDomain.setPassword(pwd);
        userDomain.setSalt(salt);
        userDao.addUser(userDomain);
    }
}
